package com.smartfactory.sail.config;

import com.ada.base.security.entity.SysUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;

@Component
@Aspect
public class AddMethodAspect {

    private Logger logger = LoggerFactory.getLogger(AddMethodAspect.class);

    @Pointcut("execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.insert(..)) || execution(* com.baomidou.mybatisplus.extension.service.IService.saveBatch(java.util.Collection))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object sendState(ProceedingJoinPoint joinPoint) throws Throwable {
        /*SysUser current = CurrentUserContext.current();
        if (current == null) {
            current = new SysUser(8L,"王巨壁","12345",new ArrayList<>());
        }*/
        SysUser current = new SysUser(8L,"王巨壁","12345",new ArrayList<>());
        String username = current.getUsername();
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            Object arg = args[0];
            if (arg instanceof Collection) {
                Collection collection = (Collection) arg;
                collection.forEach(o -> pro(o, username));
            }
            pro(arg, username);
        }

        return joinPoint.proceed(args);
    }

    private void pro(Object arg, String username) {
        try {
            Method setCreateUser = arg.getClass().getDeclaredMethod("setCreateUser", String.class);
            setCreateUser.invoke(arg, username);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.warn(e.getMessage());
        }

        try {
            Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", String.class);
            setUpdateUser.invoke(arg, username);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.warn(e.getMessage());
        }
    }
}
